package com.alex.controller.admin;

import com.alex.pojo.Book;
import com.alex.pojo.User;
import com.alex.service.BookService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.util.List;

@Controller
@RequestMapping("/admin")
public class BookAdminController {
    private final String REDIRECTBOOKS = "redirect:/admin/book/list";

    @Resource
    private BookService bookService;

    @RequestMapping("/book/list")
    public String bookList(@RequestParam(value = "bn", required = false) String bn, Model model) {
        List<Book> books = null;
        System.out.println("search keyword bn: " + bn);
        if (bn == null || bn.isEmpty()) {
            books = bookService.getAll();
        } else {
            books = bookService.searchByName(bn);
        }
        model.addAttribute("books", books);
        model.addAttribute("bn", bn);
        return "admin/list";
    }

    @RequestMapping("/book/add")
    public String toAdd() {
        return "admin/add";
    }

    @RequestMapping("/book/doAdd")
    public String doAdd(Book book) {
        System.out.println(book);
        bookService.add(book);
        return REDIRECTBOOKS;
    }

    @RequestMapping("/book/update")
    public String toUpdate(@RequestParam("isbn") String isbn, Model model) {
        System.out.println(model.getAttribute("book"));
//        Book book = bookService.get(isbn);
//        model.addAttribute("book", book);
        return "admin/update";
    }

    @RequestMapping("/book/doUpdate")
    public String doUpdate(Book book) {
        System.out.println("do update: " + book);
        bookService.update(book);
        return REDIRECTBOOKS;
    }
    @ModelAttribute // @ModelAttribute 修饰的方法其实是一个拦截器,该类下其他方法执行前都会调用此方法
    public void getBook(@RequestParam(value = "isbn", required = false) String isbn, Model model) {
        System.out.println("@ModelAttribute -> about book: " + isbn );
        if (isbn != null) {
            Book book = bookService.get(isbn);
            model.addAttribute("book", book);
            model.addAttribute("aboutBook", book);
        }
    }
    @ModelAttribute
    public void testModelAttribute() {
        System.out.println("testModelAttribute");
    }

    @RequestMapping("/book/del")
    public String del(String isbn) {
        System.out.println("delete book isbn: " + isbn);
        bookService.delete(isbn);
        return REDIRECTBOOKS;
    }

}
